<?php

namespace app\service\api;

use app\model\api\ah\AhAmulet;
use app\model\api\ah\AhAmuletLevel;
use app\model\api\ah\AhCareer;
use app\model\api\ah\AhEquipment;
use app\model\api\ah\AhGemstone;
use app\model\api\ah\AhLabel;
use app\model\api\ah\AhOutfit;
use app\model\api\ah\AhOutfitPlayStyle;
use app\model\api\ah\AhPlayStyle;
use app\model\api\ah\AhSkill;
use app\model\api\ah\XmUser;
use app\model\api\ah\XmUserCollect;
use app\model\api\ah\XmUserLikes;
use think\facade\Db;

class AhService
{
    public function indexList($data){
        $model = new AhOutfit();
        $user_likes = (new XmUserLikes())->cache(true)->where('user_id',$data['user_id'])->column('outfit_id');
        $user_collect = (new XmUserCollect())->cache(true)->where('user_id',$data['user_id'])->column('outfit_id');
        $role_list = (new AhCareer())->cache(true)->column('id,name,avatar,icon,picture,role_id','id');
        $label_list = (new AhLabel())->cache(true)->column('id,value,value_color,bg_color','id');
        $list = $model
            ->with(['user', 'label', 'play'])
            ->withCache(30);
        $where = [];
        $order = "";
        //判断角色id
        if (isset($data['role_id']) && $data['role_id'] != '') {
            $where[] = ['role_id', '=', $data['role_id']];
        }
        //判断玩法
        if (isset($data['play_style_id']) )
        {
            $data['play_style_id'] = array_filter($data['play_style_id']);
            if(count($data['play_style_id'])>0){
                $list = $list->hasWhere('playSearch', function ($query) use ($data) {
                    return $query->whereIn('play_style_id', $data['play_style_id']);
                });
            }
        }
        //判断排序类型
        switch ($data['order']) {
            case "hot"://热门
                $where[] = ['is_recommend', '=', 'yes'];
                $where[] = ['is_publish', '=', 'yes'];
                $order .= "likes_number desc ";
                break;
            case "new"://最新
                $where[] = ['is_recommend', '=', 'yes'];
                $where[] = ['is_publish', '=', 'yes'];
                $order .= 'create_time desc ';
                break;
            case "collect"://收藏
                $where[] = ['is_publish', '=', 'yes'];
                $ids = (new XmUserCollect())->cache(true)->where('user_id', $data['user_id'])->column('outfit_id');
                $list->whereIn('id', $ids);
                break;
            case "create"://创建
                $where[] = ['user_id', '=', $data['user_id']];
                $order .= "create_time desc ";
                break;
        }
        $order .= "sort desc";
        $list = $list
            ->field('id,name,label_id,user_id,role_id,likes_number,attr,create_time,is_publish,is_recommend')
            ->where($where)
            ->cache(true)
            ->order($order)
            ->paginate($data['limit'])
            ->toArray();
        //去除数组一级多余字段

        //去除数组二级多余字段
        $list['data'] = array_map(function ($item) use ($data,$user_likes,$user_collect,$role_list,$label_list) {
            if (in_array($item['id'], $user_collect)) {
                $item['collect'] = 'yes';
            } else {
                $item['collect'] = 'no';
            }
            if (in_array($item['id'], $user_likes)) {
                $item['likes'] = 'yes';
            } else {
                $item['likes'] = 'no';
            }
            if (isset($item['user']['create_time'])) unset($item['user']['create_time']);
            if (isset($item['user']['id'])) unset($item['user']['id']);
            if (is_null($item['user']['delete_time'])) unset($item['user']['delete_time']);
            $item['role'] =$role_list[$item['role_id']];
            if(!empty($item['label_id'])&&isset($label_list[$item['label_id']])){
                $item['label'] = $label_list[$item['label_id']];
            }else{
                $item['label'] = null;
            }
            $item['play'] = $this->changeData($item['play'], ['create_time', 'delete_time', 'pivot']);
            return $item;
        }, $list['data']);
        $list['data'] = $this->changeData(
            $list['data'],
            ['label_id', 'user_id', 'role_id']
        );
        return $list;

    }

    public function detailOutfit($data){
        $model = new AhOutfit();
        $where = [
            ['id', '=', $data['outfit_id']]
        ];
        $item = $model
            ->withCache(30)
            ->cache(true)
            ->field('is_publish,is_recommend,id,name,label_id,user_id,role_id,likes_number,description,detail,attr,create_time')
            ->where($where)
            ->find();
        if (is_object($item)) $item = $item->toArray();
        if (empty($item)) {
            return $this->error('配装不存在');
        }
        $item['create_time'] = date("Y-m-d",strtotime($item['create_time']));
        $user_collect = (new XmUserCollect())->cache(true)->where('user_id',$data['user_id'])->where('outfit_id',$data['outfit_id'])->count('id');
        $user_likes = (new XmUserLikes())->cache(true)->where('user_id',$data['user_id'])->where('outfit_id',$data['outfit_id'])->count('id');
        $item['detail'] = $this->transIcon(json_decode($item['detail'], true));
        if ($user_collect>0) {
            $item['collect'] = 'yes';
        } else {
            $item['collect'] = 'no';
        }
        if ($user_likes>0) {
            $item['likes'] = 'yes';
        } else {
            $item['likes'] = 'no';
        }
        $item['user'] = (new XmUser())->cache(true)->field("nickname,avatar,id")->where('user_id',$item['user_id'])->find();
        $item['role'] = (new AhCareer())->cache(true)->where('id',$item['role_id'])->find();
        if(!empty($item['label_id'])){
            $item['label'] = (new AhLabel())->cache(true)->where('id',$item['label_id'])->field('value,value_color,bg_color')->find();
        }
        $playIds = (new AhOutfitPlayStyle())->cache(true)->where('outfit_id',$data['outfit_id'])->column("play_style_id");
        if(count($playIds)>0){
            $item['play'] = (new AhPlayStyle())->cache(true)->whereIn('id',$playIds)->field('id,name,sort')->select();
        }else{
            $item['play'] = [];
        }
        return $item;
    }

    /**
     * json图片转换
     * @param $detail
     * @return mixed
     */
    public function transIcon($detail){
        $equipmentIcon   = (new AhEquipment())->column('icon','id');
        $amuletLevelIcon = (new AhAmuletLevel())->column('icon','id');
        $amuletIcon = (new AhAmulet())->column('icon','id');
        $skillIcon  = (new AhSkill())->column('icon','id');
        $stoneIcon  = (new AhGemstone())->column('icon','id');
        if(!empty($detail['equipment']) && is_array($detail['equipment'])){
            array_walk($detail['equipment'],function(&$equipItem,$equipKey) use ($equipmentIcon,$amuletLevelIcon,$amuletIcon,$stoneIcon){
                if($equipItem['kind'] == 999){
                    $equipItem['icon'] = $amuletLevelIcon[$equipItem['id']] ?? '';
                    if(!empty($equipItem['attr'])){
                        array_walk($equipItem['attr'],function(&$equipValue,$equipIndex) use ($amuletIcon){
                            $equipValue['icon'] = $amuletIcon[$equipValue['id']] ?? '';
                        });
                    }
                }else{
                    $equipItem['icon'] = $equipmentIcon[$equipItem['id']] ?? '';
                    if(!empty($equipItem['stone'])){
                        array_walk($equipItem['stone'],function(&$equipValue,$equipIndex) use ($stoneIcon){
                            $equipValue['icon'] = $stoneIcon[$equipValue['id']] ?? '';
                        });
                    }
                }
            });
        }

        if(!empty($detail['skills']) && is_array($detail['skills'])){
            if(!empty($detail['skills']['attack'])){
                $detail['skills']['attack']['icon'] = $skillIcon[$detail['skills']['attack']['id']] ?? '';
            }
            if(!empty($detail['skills']['skill'])){
                array_walk($detail['skills']['skill'],function(&$skillValue,$skillIndex) use ($skillIcon){
                    $skillValue['icon'] = $skillIcon[$skillValue['id']] ?? '';
                });
            }
        }

        return $detail;
    }

    public function changeData($data, $filter = [], $decode_data = [])
    {
        foreach ($data as &$v) {
            foreach ($filter as $item) {
                if (is_null($v[$item])) unset($v[$item]);
                if (isset($v[$item])) unset($v[$item]);
            }
            foreach ($decode_data as $item) {
                if (isset($v[$item])) $v[$item] = json_decode($v[$item], true);
            }
            $v['delete_time'] = 1;
            unset($v['delete_time']);
            if (isset($v['create_time'])) $v['create_time'] = date("Y-m-d", strtotime($v['create_time']));
        }
        return $data;
    }
}